﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.HtmlControls;
using System.Transactions;

public partial class Main_ServiceInvoice_PurchaseOrder : System.Web.UI.Page
{
    Datautility DU = new Datautility();
    string strsql = string.Empty;
    int intRowCounter = 1;
    List<string> LstRowCount;
    List<string> LstServices;
    List<string> LstTaxable;
    List<string> LstHidChildId;
    List<string> LstDescription;
    List<string> LstUnit;
    List<string> LstRate;
    List<string> LstServiceTax;
    List<string> LstPECess;
    List<string> LstHECess;
    List<string> LstTotalAmt;

    protected override void LoadViewState(object savedState)
    {
        base.LoadViewState(savedState);
        _OverrideAddMore();

    }
    //protected override void OnLoad(EventArgs e)
    //{
    //    base.OnLoad(e);
    //    _OverrideAddMore();
    //}
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["userid"] == null)
        {
            Response.Redirect("~/SessionExpired.aspx");
        }
        if (!IsPostBack)
        {
            //**************Set Minimum and maximum date calender Control********
            AccountSettings.setMinMaxDate(form1);
            //********************End **********
            LstRowCount = new List<string>();
            ViewState["LstRowCount"] = LstRowCount;

            LstServices = new List<string>();
            ViewState["LstServices"] = LstServices;

            LstTaxable = new List<string>();
            ViewState["LstTaxable"] = LstTaxable;

            LstHidChildId = new List<string>();
            ViewState["LstHidChildId"] = LstHidChildId;

            LstDescription = new List<string>();
            ViewState["LstDescription"] = LstDescription;

            LstUnit = new List<string>();
            ViewState["LstUnit"] = LstUnit;


            LstRate = new List<string>();
            ViewState["LstRate"] = LstRate;

            LstServiceTax = new List<string>();
            ViewState["LstServiceTax"] = LstServiceTax;

            LstPECess = new List<string>();
            ViewState["LstPECess"] = LstPECess;

            LstHECess = new List<string>();
            ViewState["LstHECess"] = LstHECess;

            LstTotalAmt = new List<string>();
            ViewState["LstTotalAmt"] = LstTotalAmt;

            _BindFormat();
            _BindCustomerLedger();
            _BindServices(ddlService1);
            //txtDate.Text = string.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(System.DateTime.Now));
            _GetServicePEHETax(Session["CURRENTDATE"].ToString());
            _BindVoucherNumber(ddlFormat.SelectedValue);
        }
    }
    private void _BindFormat()
    {
        SqlParameter[] sapram ={
                                  new SqlParameter("@FormatId","0")
                             };
        DataTable DTFormat = DU.getdatausingprocedure("USP_IVC_GetPurchaseOrderFormat", sapram);
        ddlFormat.DataSource = DTFormat;
        ddlFormat.DataTextField = "FormatName";
        ddlFormat.DataValueField = "FormatId";
        ddlFormat.DataBind();
    }
    private void _BindCustomerLedger()
    {
        DataTable DTFormat = DU.getdatausingprocedure("USP_IVC_GetCustomerLedger");
        if (DTFormat.Rows.Count > 0)
        {
            ddlClients.DataSource = DTFormat;
            ddlClients.DataTextField = "LNAME";
            ddlClients.DataValueField = "LID";
            ddlClients.DataBind();
            ddlClients.Items.Insert(0, new ListItem("-Select Client-", "0"));
        }
    }

    private void _GenerateDynamicTableControl()
    {
        DataTable DTFormat = _GetPurchaseFormatDetails(ddlFormat.SelectedValue);
        if (DTFormat.Rows.Count > 0)
        {
            if (hidFormatSecond.Value != hidFormatFrist.Value)
            {
                _DeleteTableRows();
                if (Convert.ToBoolean(DTFormat.Rows[0]["TaxLevel"]) == false)
                {
                    if (Convert.ToBoolean(DTFormat.Rows[0]["Description"]) == true && Convert.ToBoolean(DTFormat.Rows[0]["UOM"]) == false && Convert.ToDouble(DTFormat.Rows[0]["DiscountLevel"]) == 0)
                    {
                        HtmlTableRow HTRowHeader = new HtmlTableRow();
                        HtmlTableCell HTCellHeader1 = new HtmlTableCell();
                        HTCellHeader1.InnerHtml = "<b>Nature of Service</b>";
                        HTCellHeader1.Width = "20%";
                        HTCellHeader1.Style.Add("class", "headtd");

                        HtmlTableCell HTCellHeader2 = new HtmlTableCell();
                        HTCellHeader2.InnerHtml = "<b>Descriptions</b>";
                        HTCellHeader2.Width = "20%";
                        HTCellHeader2.Style.Add("class", "headtd");


                        HtmlTableCell HTCellHeader3 = new HtmlTableCell();
                        HTCellHeader3.InnerHtml = "<b>Unit</b>";
                        HTCellHeader3.Width = "20%";
                        HTCellHeader3.Style.Add("class", "headtd");


                        HtmlTableCell HTCellHeader4 = new HtmlTableCell();
                        HTCellHeader4.InnerHtml = "<b>Rate</b>";
                        HTCellHeader4.Width = "20%";
                        HTCellHeader4.Style.Add("class", "headtd");

                        HtmlTableCell HTCellHeader5 = new HtmlTableCell();
                        HTCellHeader5.InnerHtml = "<b>Total Amount</b>";
                        HTCellHeader5.Width = "20%";
                        HTCellHeader5.Style.Add("class", "headtd");


                        HTRowHeader.Cells.Add(HTCellHeader1);
                        HTRowHeader.Cells.Add(HTCellHeader2);
                        HTRowHeader.Cells.Add(HTCellHeader3);
                        HTRowHeader.Cells.Add(HTCellHeader4);
                        HTRowHeader.Cells.Add(HTCellHeader5);
                        tblPODetails.Rows.Add(HTRowHeader);

                    }
                    else if (Convert.ToBoolean(DTFormat.Rows[0]["Description"]) == false && Convert.ToBoolean(DTFormat.Rows[0]["UOM"]) == true && Convert.ToDouble(DTFormat.Rows[0]["DiscountLevel"]) == 0)
                    {
                        HtmlTableRow HTRowHeader = new HtmlTableRow();
                        HtmlTableCell HTCellHeader1 = new HtmlTableCell();
                        HTCellHeader1.InnerHtml = "<b>Nature of Service</b>";
                        HTCellHeader1.Width = "20%";
                        HTCellHeader1.Style.Add("class", "headtd");

                        HtmlTableCell HTCellHeader2 = new HtmlTableCell();
                        HTCellHeader2.InnerHtml = "<b>Unit Of Measurement</b>";
                        HTCellHeader2.Width = "20%";
                        HTCellHeader2.Style.Add("class", "headtd");


                        HtmlTableCell HTCellHeader3 = new HtmlTableCell();
                        HTCellHeader3.InnerHtml = "<b>Unit</b>";
                        HTCellHeader3.Width = "20%";
                        HTCellHeader3.Style.Add("class", "headtd");


                        HtmlTableCell HTCellHeader4 = new HtmlTableCell();
                        HTCellHeader4.InnerHtml = "<b>Rate</b>";
                        HTCellHeader4.Width = "20%";
                        HTCellHeader4.Style.Add("class", "headtd");

                        HtmlTableCell HTCellHeader5 = new HtmlTableCell();
                        HTCellHeader5.InnerHtml = "<b>Total Amount</b>";
                        HTCellHeader5.Width = "20%";
                        HTCellHeader5.Style.Add("class", "headtd");


                        HTRowHeader.Cells.Add(HTCellHeader1);
                        HTRowHeader.Cells.Add(HTCellHeader2);
                        HTRowHeader.Cells.Add(HTCellHeader3);
                        HTRowHeader.Cells.Add(HTCellHeader4);
                        HTRowHeader.Cells.Add(HTCellHeader5);
                        tblPODetails.Rows.Add(HTRowHeader);

                    }
                    else if (Convert.ToBoolean(DTFormat.Rows[0]["Description"]) == true && Convert.ToBoolean(DTFormat.Rows[0]["UOM"]) == true && Convert.ToDouble(DTFormat.Rows[0]["DiscountLevel"]) == 0)
                    {
                        HtmlTableRow HTRowHeader = new HtmlTableRow();
                        HtmlTableCell HTCellHeader1 = new HtmlTableCell();
                        HTCellHeader1.InnerHtml = "<b>Nature of Service</b>";
                        HTCellHeader1.Width = "20%";
                        HTCellHeader1.Style.Add("class", "headtd");

                        HtmlTableCell HTCellHeader2 = new HtmlTableCell();
                        HTCellHeader2.InnerHtml = "<b>Descriptions</b>";
                        HTCellHeader2.Width = "20%";
                        HTCellHeader2.Style.Add("class", "headtd");


                        HtmlTableCell HTCellHeader3 = new HtmlTableCell();
                        HTCellHeader3.InnerHtml = "<b>Unit Of Measurement</b>";
                        HTCellHeader3.Width = "15%";
                        HTCellHeader3.Style.Add("class", "headtd");

                        HtmlTableCell HTCellHeader4 = new HtmlTableCell();
                        HTCellHeader4.InnerHtml = "<b>Unit</b>";
                        HTCellHeader4.Width = "15%";
                        HTCellHeader4.Style.Add("class", "headtd");


                        HtmlTableCell HTCellHeader5 = new HtmlTableCell();
                        HTCellHeader5.InnerHtml = "<b>Rate</b>";
                        HTCellHeader5.Width = "15%";
                        HTCellHeader5.Style.Add("class", "headtd");

                        HtmlTableCell HTCellHeader6 = new HtmlTableCell();
                        HTCellHeader6.InnerHtml = "<b>Total Amount</b>";
                        HTCellHeader6.Width = "15%";
                        HTCellHeader6.Style.Add("class", "headtd");


                        HTRowHeader.Cells.Add(HTCellHeader1);
                        HTRowHeader.Cells.Add(HTCellHeader2);
                        HTRowHeader.Cells.Add(HTCellHeader3);
                        HTRowHeader.Cells.Add(HTCellHeader4);
                        HTRowHeader.Cells.Add(HTCellHeader5);
                        HTRowHeader.Cells.Add(HTCellHeader6);
                        tblPODetails.Rows.Add(HTRowHeader);
                    }
                    else if (Convert.ToBoolean(DTFormat.Rows[0]["Description"]) == true && Convert.ToBoolean(DTFormat.Rows[0]["UOM"]) == true && Convert.ToDouble(DTFormat.Rows[0]["DiscountLevel"]) == 0)
                    {
                        HtmlTableRow HTRowHeader = new HtmlTableRow();
                        HtmlTableCell HTCellHeader1 = new HtmlTableCell();
                        HTCellHeader1.InnerHtml = "<b>Nature of Service</b>";
                        HTCellHeader1.Width = "20%";
                        HTCellHeader1.Style.Add("class", "headtd");

                        HtmlTableCell HTCellHeader2 = new HtmlTableCell();
                        HTCellHeader2.InnerHtml = "<b>Descriptions</b>";
                        HTCellHeader2.Width = "20%";
                        HTCellHeader2.Style.Add("class", "headtd");


                        HtmlTableCell HTCellHeader3 = new HtmlTableCell();
                        HTCellHeader3.InnerHtml = "<b>Unit Of Measurement</b>";
                        HTCellHeader3.Width = "15%";
                        HTCellHeader3.Style.Add("class", "headtd");

                        HtmlTableCell HTCellHeader4 = new HtmlTableCell();
                        HTCellHeader4.InnerHtml = "<b>Unit</b>";
                        HTCellHeader4.Width = "15%";
                        HTCellHeader4.Style.Add("class", "headtd");


                        HtmlTableCell HTCellHeader5 = new HtmlTableCell();
                        HTCellHeader5.InnerHtml = "<b>Rate</b>";
                        HTCellHeader5.Width = "15%";
                        HTCellHeader5.Style.Add("class", "headtd");

                        HtmlTableCell HTCellHeader6 = new HtmlTableCell();
                        HTCellHeader6.InnerHtml = "<b>Total Amount</b>";
                        HTCellHeader6.Width = "15%";
                        HTCellHeader6.Style.Add("class", "headtd");


                        HTRowHeader.Cells.Add(HTCellHeader1);
                        HTRowHeader.Cells.Add(HTCellHeader2);
                        HTRowHeader.Cells.Add(HTCellHeader3);
                        HTRowHeader.Cells.Add(HTCellHeader4);
                        HTRowHeader.Cells.Add(HTCellHeader5);
                        HTRowHeader.Cells.Add(HTCellHeader6);
                        tblPODetails.Rows.Add(HTRowHeader);
                    }
                    else if (Convert.ToBoolean(DTFormat.Rows[0]["Description"]) == true && Convert.ToBoolean(DTFormat.Rows[0]["UOM"]) == false && Convert.ToDouble(DTFormat.Rows[0]["DiscountLevel"]) == 2)
                    {
                        HtmlTableRow HTRowHeader = new HtmlTableRow();
                        HtmlTableCell HTCellHeader1 = new HtmlTableCell();
                        HTCellHeader1.InnerHtml = "<b>Nature of Service</b>";
                        HTCellHeader1.Width = "20%";
                        HTCellHeader1.Style.Add("class", "headtd");

                        HtmlTableCell HTCellHeader2 = new HtmlTableCell();
                        HTCellHeader2.InnerHtml = "<b>Descriptions</b>";
                        HTCellHeader2.Width = "15%";
                        HTCellHeader2.Style.Add("class", "headtd");


                        HtmlTableCell HTCellHeader3 = new HtmlTableCell();
                        HTCellHeader3.InnerHtml = "<b>Unit</b>";
                        HTCellHeader3.Width = "15%";
                        HTCellHeader3.Style.Add("class", "headtd");


                        HtmlTableCell HTCellHeader4 = new HtmlTableCell();
                        HTCellHeader4.InnerHtml = "<b>Rate</b>";
                        HTCellHeader4.Width = "15%";
                        HTCellHeader4.Style.Add("class", "headtd");

                        HtmlTableCell HTCellHeader5 = new HtmlTableCell();
                        HTCellHeader5.InnerHtml = "<b>Discount(%)</b>";
                        HTCellHeader5.Width = "10%";
                        HTCellHeader5.Style.Add("class", "headtd");


                        HtmlTableCell HTCellHeader6 = new HtmlTableCell();
                        HTCellHeader6.InnerHtml = "<b>Discount Amt</b>";
                        HTCellHeader6.Width = "10%";
                        HTCellHeader6.Style.Add("class", "headtd");


                        HtmlTableCell HTCellHeader7 = new HtmlTableCell();
                        HTCellHeader7.InnerHtml = "<b>Total Amt</b>";
                        HTCellHeader7.Width = "15%";
                        HTCellHeader7.Style.Add("class", "headtd");


                        HTRowHeader.Cells.Add(HTCellHeader1);
                        HTRowHeader.Cells.Add(HTCellHeader2);
                        HTRowHeader.Cells.Add(HTCellHeader3);
                        HTRowHeader.Cells.Add(HTCellHeader4);
                        HTRowHeader.Cells.Add(HTCellHeader5);
                        HTRowHeader.Cells.Add(HTCellHeader6);
                        HTRowHeader.Cells.Add(HTCellHeader7);
                        tblPODetails.Rows.Add(HTRowHeader);

                    }
                }
            }
        }
        GridView1.DataSource = DTFormat;
        GridView1.DataBind();
    }
    private void _AddMoreRow()
    {
        intRowCounter++;
        HtmlTableRow HTRow = new HtmlTableRow();

        HtmlTableCell HTCell1 = new HtmlTableCell();
        DropDownList ddlService = new DropDownList();
        ddlService.ID = "ddlService" + intRowCounter.ToString();
        ddlService.CssClass = "dropdown";
        ddlService.Width = Unit.Percentage(98);
        _BindServices(ddlService);
        ddlService.AutoPostBack = true;
        ddlService.SelectedIndexChanged += new EventHandler(ddlService_SelectedIndexChanged);
        HiddenField hidChkTaxable = new HiddenField();
        hidChkTaxable.ID = "hidChkTaxable" + intRowCounter.ToString();
        HiddenField hidPOChildId = new HiddenField();
        hidPOChildId.ID = "hidPOChildId" + intRowCounter.ToString();

        HTCell1.Controls.Add(ddlService);
        HTCell1.Controls.Add(hidChkTaxable);
        HTCell1.Controls.Add(hidPOChildId);
        LstRowCount.Add(intRowCounter.ToString());
        LstServices.Add(ddlService.ID);
        LstTaxable.Add(hidChkTaxable.ID);
        LstHidChildId.Add(hidPOChildId.ID);

        HtmlTableCell HTCell2 = new HtmlTableCell();
        TextBox txtDescription = new TextBox();
        txtDescription.ID = "txtDescription" + intRowCounter.ToString();
        txtDescription.CssClass = "input";
        txtDescription.Width = Unit.Percentage(98);
        HTCell2.Controls.Add(txtDescription);
        LstDescription.Add(txtDescription.ID);

        HtmlTableCell HTCell3 = new HtmlTableCell();
        TextBox txtUnit = new TextBox();
        txtUnit.ID = "txtUnit" + intRowCounter.ToString();
        txtUnit.CssClass = "inputnumber";
        txtUnit.Width = Unit.Percentage(98);
        txtUnit.Attributes.Add("onKeyPress", "return isNumberKey(this.id,event);");
        txtUnit.Attributes.Add("onblur", "return CalculateAmount();");
        HTCell3.Controls.Add(txtUnit);
        LstUnit.Add(txtUnit.ID);

        HtmlTableCell HTCell4 = new HtmlTableCell();
        TextBox txtRate = new TextBox();
        txtRate.ID = "txtRate" + intRowCounter.ToString();
        txtRate.CssClass = "inputnumber";
        txtRate.Width = Unit.Percentage(98);
        txtRate.Attributes.Add("onKeyPress", "return isNumberKey(this.id,event);");
        txtRate.Attributes.Add("onblur", "return CalculateAmount();");
        HiddenField hidServiceTaxAmt = new HiddenField();
        hidServiceTaxAmt.ID = "hidServiceTaxAmt" + intRowCounter.ToString();
        HiddenField hidPECessAmt = new HiddenField();
        hidPECessAmt.ID = "hidPECessAmt" + intRowCounter.ToString();
        HiddenField hidHECessAmt = new HiddenField();
        hidHECessAmt.ID = "hidHECessAmt" + intRowCounter.ToString();
        hidPOChildId.Value = "0";
        HTCell4.Controls.Add(txtRate);
        HTCell4.Controls.Add(hidServiceTaxAmt);
        HTCell4.Controls.Add(hidPECessAmt);
        HTCell4.Controls.Add(hidHECessAmt);
        LstRate.Add(txtRate.ID);
        LstServiceTax.Add(hidServiceTaxAmt.ID);
        LstPECess.Add(hidPECessAmt.ID);
        LstHECess.Add(hidHECessAmt.ID);

        HtmlTableCell HTCell5 = new HtmlTableCell();
        TextBox txtTotalAmt = new TextBox();
        txtTotalAmt.ID = "txtTotalAmt" + intRowCounter.ToString();
        txtTotalAmt.CssClass = "DisableInputNumber";
        txtTotalAmt.Width = Unit.Percentage(98);
        txtTotalAmt.Attributes.Add("onkeydown", "return EnabledTabKey(this.id,event);");
        HTCell5.Controls.Add(txtTotalAmt);
        LstTotalAmt.Add(txtTotalAmt.ID);

        HTRow.Cells.Add(HTCell1);
        HTRow.Cells.Add(HTCell2);
        HTRow.Cells.Add(HTCell3);
        HTRow.Cells.Add(HTCell4);
        HTRow.Cells.Add(HTCell5);
        tblPODetails.Rows.Add(HTRow);

        hidControl.Value = intRowCounter.ToString();


        ViewState["LstRowCount"] = LstRowCount;
        ViewState["LstServices"] = LstServices;
        ViewState["LstTaxable"] = LstTaxable;
        ViewState["LstHidChildId"] = LstHidChildId;
        ViewState["LstDescription"] = LstDescription;
        ViewState["LstUnit"] = LstUnit;
        ViewState["LstRate"] = LstRate;
        ViewState["LstServiceTax"] = LstServiceTax;
        ViewState["LstPECess"] = LstPECess;
        ViewState["LstHECess"] = LstHECess;
        ViewState["LstTotalAmt"] = LstTotalAmt;

    }
    private void _OverrideAddMore()
    {
        LstRowCount = (List<string>)ViewState["LstRowCount"];
        LstServices = (List<string>)ViewState["LstServices"];
        LstTaxable = (List<string>)ViewState["LstTaxable"];
        LstHidChildId = (List<string>)ViewState["LstHidChildId"];
        LstDescription = (List<string>)ViewState["LstDescription"];
        LstUnit = (List<string>)ViewState["LstUnit"];
        LstRate = (List<string>)ViewState["LstRate"];
        LstServiceTax = (List<string>)ViewState["LstServiceTax"];
        LstPECess = (List<string>)ViewState["LstPECess"];
        LstHECess = (List<string>)ViewState["LstHECess"];
        LstTotalAmt = (List<string>)ViewState["LstTotalAmt"];
        if (LstRowCount != null)
        {
            int Count = Convert.ToInt32(LstRowCount.Count);
            for (int i = 0; i < Count; i++)
            {
                intRowCounter++;
                HtmlTableRow HTRow = new HtmlTableRow();

                HtmlTableCell HTCell1 = new HtmlTableCell();
                DropDownList ddlService = new DropDownList();
                ddlService.ID = LstServices[i].ToString();
                ddlService.CssClass = "dropdown";
                ddlService.Width = Unit.Percentage(98);
                _BindServices(ddlService);
                ddlService.AutoPostBack = true;
                ddlService.SelectedIndexChanged += new EventHandler(ddlService_SelectedIndexChanged);
                HiddenField hidChkTaxable = new HiddenField();
                hidChkTaxable.ID = LstTaxable[i].ToString();
                HiddenField hidPOChildId = new HiddenField();
                hidPOChildId.ID = LstHidChildId[i].ToString();
                hidPOChildId.Value = "0";
                HTCell1.Controls.Add(ddlService);
                HTCell1.Controls.Add(hidChkTaxable);
                HTCell1.Controls.Add(hidPOChildId);

                HtmlTableCell HTCell2 = new HtmlTableCell();
                TextBox txtDescription = new TextBox();
                txtDescription.ID = LstDescription[i].ToString();
                txtDescription.CssClass = "input";
                txtDescription.Width = Unit.Percentage(98);
                HTCell2.Controls.Add(txtDescription);


                HtmlTableCell HTCell3 = new HtmlTableCell();
                TextBox txtUnit = new TextBox();
                txtUnit.ID = LstUnit[i].ToString();
                txtUnit.CssClass = "inputnumber";
                txtUnit.Width = Unit.Percentage(98);
                txtUnit.Attributes.Add("onKeyPress", "return isNumberKey(this.id,event);");
                txtUnit.Attributes.Add("onblur", "return CalculateAmount();");
                HTCell3.Controls.Add(txtUnit);


                HtmlTableCell HTCell4 = new HtmlTableCell();
                TextBox txtRate = new TextBox();
                txtRate.ID = LstRate[i].ToString();
                txtRate.CssClass = "inputnumber";
                txtRate.Width = Unit.Percentage(98);
                txtRate.Attributes.Add("onKeyPress", "return isNumberKey(this.id,event);");
                txtRate.Attributes.Add("onblur", "return CalculateAmount();");
                HiddenField hidServiceTaxAmt = new HiddenField();
                hidServiceTaxAmt.ID = LstServiceTax[i].ToString();
                HiddenField hidPECessAmt = new HiddenField();
                hidPECessAmt.ID = LstPECess[i].ToString();
                HiddenField hidHECessAmt = new HiddenField();
                hidHECessAmt.ID = LstHECess[i].ToString();
                HTCell4.Controls.Add(txtRate);
                HTCell4.Controls.Add(hidServiceTaxAmt);
                HTCell4.Controls.Add(hidPECessAmt);
                HTCell4.Controls.Add(hidHECessAmt);

                HtmlTableCell HTCell5 = new HtmlTableCell();
                TextBox txtTotalAmt = new TextBox();
                txtTotalAmt.ID = LstTotalAmt[i].ToString();
                txtTotalAmt.CssClass = "DisableInputNumber";
                txtTotalAmt.Width = Unit.Percentage(98);
                txtTotalAmt.Attributes.Add("onkeydown", "return EnabledTabKey(this.id,event);");
                HTCell5.Controls.Add(txtTotalAmt);


                HTRow.Cells.Add(HTCell1);
                HTRow.Cells.Add(HTCell2);
                HTRow.Cells.Add(HTCell3);
                HTRow.Cells.Add(HTCell4);
                HTRow.Cells.Add(HTCell5);
                tblPODetails.Rows.Add(HTRow);

            }
        }
    }
    private DataTable _GetPurchaseFormatDetails(string strFormatId)
    {
        DataTable DTFormat = new DataTable();
        SqlParameter[] sparam ={
                                   new  SqlParameter("@FormatId",strFormatId)
                               };
        DTFormat = DU.getdatausingprocedure("USP_IVC_GetPurchaseOrderFormatSettings", sparam);
        return DTFormat;
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            string strMsg = string.Empty;
            using (TransactionScope scope = new TransactionScope())
            {
                strMsg = _SavePurchaseOrder_Main(hidPOId.Value);
                scope.Complete();
            }
            if (strMsg == "Save")
            {
                Response.Redirect("PurchaseOrder.aspx");
            }
            else
            {
                lblMsg.Text = "Error While Saving Records";
            }

        }
        catch (Exception ex)
        {
            lblMsg.Text = ex.Message;
        }
    }
    protected void ddlFormat_SelectedIndexChanged(object sender, EventArgs e)
    {
        _BindVoucherNumber(ddlFormat.SelectedValue);
    }
    private void _DeleteTableRows()
    {
        if (tblPODetails.Rows.Count > 0)
        {
            for (int i = 0; i < tblPODetails.Rows.Count; i++)
            {
                tblPODetails.Rows.RemoveAt(i);
            }
        }
    }
    protected void btnAddMore_Click(object sender, EventArgs e)
    {
        _AddMoreRow();
    }
    private void _BindServices(DropDownList ddl)
    {
        DataTable DT = DU.getdatausingprocedure("USP_IVC_GetAllServices");
        ddl.DataSource = DT;
        ddl.DataTextField = "SERVICENAME";
        ddl.DataValueField = "SERVICEID";
        ddl.DataBind();
        ddl.Items.Insert(0, new ListItem("-Select-", "0"));
    }

    private string _GetServiceLedgerId(string strServiceId)
    {
        string strLedgerId = string.Empty;
        if (strServiceId != string.Empty)
        {
            strsql = "SELECT LEDGERID FROM IVC_SERVICEMASTER WHERE SERVICEID='" + strServiceId + "'";
            DataTable DTLedger = DU.getdata(strsql);
            if (DTLedger.Rows.Count > 0)
            {
                strLedgerId = DTLedger.Rows[0]["LEDGERID"].ToString();
            }
        }
        return strLedgerId;
    }
    protected void ddlService_SelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList ddl = (DropDownList)sender;
        if (ddl.SelectedValue != "0")
        {
            string ddlid = ddl.ID.ToString().Substring(10);
            int rowIndex = Convert.ToInt32(ddlid.ToString());
            strsql = "select taxability,subclass from IVC_SERVICEMASTER where serviceid='" + ddl.SelectedValue + "'";
            DataTable DTTax = DU.getdata(strsql);
            HiddenField hidChkTaxable = (HiddenField)tblPODetails.Rows[rowIndex].FindControl("hidChkTaxable" + rowIndex.ToString());
            if (DTTax.Rows.Count > 0)
            {
                if (DTTax.Rows[0]["taxability"].ToString() == "0" && DTTax.Rows[0]["subclass"].ToString() == "1")
                {
                    hidChkTaxable.Value = "1";
                }
                else
                {
                    hidChkTaxable.Value = "0";
                }
            }
        }
        ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "CalculateAmount();", true);
    }
    private void _GetServicePEHETax(string strCurrentDate)
    {
        if (strCurrentDate != string.Empty)
        {
            string[] str = strCurrentDate.ToString().Split('/');
            strCurrentDate = str[1] + "/" + str[0] + "/" + str[2];
            SqlParameter[] gettaxrate = 
                                        {
                                            new SqlParameter("@CURRENTDATE",strCurrentDate)
                                        };
            DataTable dtFillTaxes = DU.getdatausingprocedure("USP_IVC_GetCurrentServiceTaxRate", gettaxrate);
            if (dtFillTaxes.Rows.Count > 0)
            {
                lblServiceTaxRate.Text = string.Format("{0:0.00}", Convert.ToDouble(dtFillTaxes.Rows[0]["SERVICETAX"].ToString())) + " %";
                lblPECessRate.Text = string.Format("{0:0.00}", Convert.ToDouble(dtFillTaxes.Rows[0]["PCess"].ToString())) + " %";
                lblHECessRate.Text = string.Format("{0:0.00}", Convert.ToDouble(dtFillTaxes.Rows[0]["HCess"].ToString())) + " %";

                hidServiceTaxRate.Value = string.Format("{0:0.00}", Convert.ToDouble(dtFillTaxes.Rows[0]["SERVICETAX"].ToString()));
                hidPECessRate.Value = string.Format("{0:0.00}", Convert.ToDouble(dtFillTaxes.Rows[0]["PCess"].ToString()));
                hidHECessRate.Value = string.Format("{0:0.00}", Convert.ToDouble(dtFillTaxes.Rows[0]["HCess"].ToString()));
            }
        }
    }
    protected void txtDate_TextChanged(object sender, EventArgs e)
    {
        _GetServicePEHETax(txtDate.Text);
    }
    private void _BindVoucherNumber(string strFormatId)
    {
        if (strFormatId != string.Empty)
        {
            if (strFormatId != "0")
            {
                SqlParameter[] sparam ={
                                           new  SqlParameter("@FORMATID",strFormatId),
                                           new SqlParameter("@FINYEAR",Session["FINYEAR"].ToString())
                                       };
                DataTable DTVoucher = DU.getdatausingprocedure("USP_IVC_GetMaxPurchaseOrderNumber", sparam);
                if (DTVoucher.Rows.Count > 0)
                {
                    txtPrefix.Text = DTVoucher.Rows[0]["PREFIX"].ToString();
                    txtVoucher.Text = DTVoucher.Rows[0]["STARTNUMBER"].ToString();
                    txtSuffix.Text = DTVoucher.Rows[0]["SUFFIX"].ToString();
                }
                else
                {
                    txtPrefix.Text = "";
                    txtVoucher.Text = "";
                    txtSuffix.Text = "";
                }
            }
            else
            {
                txtPrefix.Text = "";
                txtVoucher.Text = "";
                txtSuffix.Text = "";
            }
        }
    }
    private string _SavePurchaseOrder_Main(string strPOId)
    {
        string strMsg = string.Empty;
        try
        {
            if (strPOId != string.Empty)
            {
                string strPoDate = string.Empty;
                if (txtDate.Text != string.Empty)
                {
                    string[] str = txtDate.Text.Split('/');
                    strPoDate = str[1] + "/" + str[0] + "/" + str[2];
                }
                if (txtCreditDay.Text == string.Empty)
                {
                    txtCreditDay.Text = "0";
                }
                if (ddlClients.SelectedValue != "0")
                {
                    SqlParameter[] sparam ={
                                       new SqlParameter("@POID",strPOId),
                                       new SqlParameter("@FORMATID",ddlFormat.SelectedValue),
                                       new SqlParameter("@PONUMBER",txtVoucher.Text.Trim()),
                                       new SqlParameter("@LID",ddlClients.SelectedValue),
                                       new SqlParameter("@PODATE",strPoDate),
                                       new SqlParameter("@FINYEAR",Session["FINYEAR"].ToString()),
                                       new SqlParameter("@PROIRITY",DdlPriority.SelectedItem.Text),
                                       new SqlParameter("@CASHCREDIT",rbtCashCredit.SelectedValue),
                                       new SqlParameter("@CREDITDAYS",txtCreditDay.Text),
                                       new SqlParameter("@PREPAREDBY",txtPreparedBy.Text.Trim()),
                                       new SqlParameter("@CHECHEDBY",txtCheckedBy.Text.Trim()),
                                       new SqlParameter("@NARRATION",txtNarration.Text.Trim()),
                                       new SqlParameter("@REMARKS",txtRemarks.Text.Trim()),
                                       new SqlParameter("@CNAME",Session["username"].ToString())
                                   };
                    string POId = DU.ExecuteProcedure_Scope_Identity("USP_IVC_SavePurchaseOrder_Main", sparam);
                    if (Convert.ToDouble(POId) > 0)
                    {
                        _SavePurchaseOrder_Child(POId);
                        _SavePurchaseOrder_Total(POId);
                        strMsg = "Save";
                    }
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return strMsg;
    }
    private void _SavePurchaseOrder_Child(string strPOId)
    {
        try
        {
            if (strPOId != string.Empty)
            {
                int Count = Convert.ToInt32(hidControl.Value);
                for (int i = 1; i <= Count; i++)
                {
                    DropDownList ddlService = (DropDownList)tblPODetails.Rows[i].FindControl("ddlService" + i);
                    HiddenField hidPOChildId = (HiddenField)tblPODetails.Rows[i].FindControl("hidPOChildId" + i);
                    HiddenField hidChkTaxable = (HiddenField)tblPODetails.Rows[i].FindControl("hidChkTaxable" + i);
                    HiddenField hidServiceTaxAmt = (HiddenField)tblPODetails.Rows[i].FindControl("hidServiceTaxAmt" + i);
                    HiddenField hidPECessAmt = (HiddenField)tblPODetails.Rows[i].FindControl("hidPECessAmt" + i);
                    HiddenField hidHECessAmt = (HiddenField)tblPODetails.Rows[i].FindControl("hidHECessAmt" + i);
                    TextBox txtDescription = (TextBox)tblPODetails.Rows[i].FindControl("txtDescription" + i);
                    TextBox txtUnit = (TextBox)tblPODetails.Rows[i].FindControl("txtUnit" + i);
                    TextBox txtRate = (TextBox)tblPODetails.Rows[i].FindControl("txtRate" + i);
                    TextBox txtTotalAmt = (TextBox)tblPODetails.Rows[i].FindControl("txtTotalAmt" + i);
                    if (ddlService.SelectedValue != "0" && txtTotalAmt.Text != string.Empty && Convert.ToDouble(txtTotalAmt.Text) > 0)
                    {
                        double dblTotalAmt = Convert.ToDouble(txtTotalAmt.Text.Trim()) + Convert.ToDouble(hidServiceTaxAmt.Value) + Convert.ToDouble(hidPECessAmt.Value) + Convert.ToDouble(hidHECessAmt.Value);
                        SqlParameter[] sparam ={
                                               new SqlParameter("@POCHILDID",hidPOChildId.Value),
                                               new SqlParameter("@POID",strPOId),
                                               new SqlParameter("@SERVICEID",ddlService.SelectedValue),
                                               new SqlParameter("@ADDDESC",txtDescription.Text.Trim()),
                                               new SqlParameter("@UNIT",txtUnit.Text.Trim()),
                                               new SqlParameter("@RATE",txtRate.Text.Trim()),
                                               new SqlParameter("@GROSSAMT",txtTotalAmt.Text.Trim()),
                                               new SqlParameter("@SERVICETAXAMT",hidServiceTaxAmt.Value),
                                               new SqlParameter("@CESS1AMT",hidPECessAmt.Value),
                                               new SqlParameter("@CESS2AMT",hidHECessAmt.Value),
                                               //new SqlParameter("@LTAMT",""),
                                               //new SqlParameter("@DISCOUNT",""),
                                               //new SqlParameter("@DISCOUNTRATE",""),
                                               //new SqlParameter("@SERVICECHARGERATE",""),
                                               //new SqlParameter("@SERVICECHARGEAMT",""),
                                               //new SqlParameter("@VATAMT",""),
                                               new SqlParameter("@TOTALAMT",dblTotalAmt)
                                           };
                        int result = DU.executeprocedure("USP_IVC_SavePurchaseOrder_Child", sparam);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    private void _SavePurchaseOrder_Total(string strPOId)
    {
        try
        {
            if (strPOId != string.Empty)
            {
                double dblTotalAmtBeforeTax = Convert.ToDouble(txtTotalTaxableAmt.Text.Trim()) + Convert.ToDouble(txtTotalNonTaxableAmt.Text.Trim());
                SqlParameter[] sparam ={
                                       new SqlParameter("@POID",strPOId),
                                       new SqlParameter("@TAXABLEAMT",txtTotalTaxableAmt.Text.Trim()),
                                       new SqlParameter("@NONTAXABLEAMT",txtTotalNonTaxableAmt.Text.Trim()),
                                       new SqlParameter("@TOTALAMTBEFTAX",dblTotalAmtBeforeTax),
                                       new SqlParameter("@SERVICETAXRATE",hidServiceTaxRate.Value),
                                       new SqlParameter("@SERVICETAXAMT",txtTotalServiceTax.Text.Trim()),
                                       new SqlParameter("@EDUCESS1RATE",hidPECessRate.Value),
                                       new SqlParameter("@EDUCESS1AMT",txtTotalPECess.Text.Trim()),
                                       new SqlParameter("@EDUCESS2RATE",hidHECessRate.Value),
                                       new SqlParameter("@EDUCESS2AMT",txtTotalHECess.Text.Trim()),
                                       //new SqlParameter("@LUXURYTAXRATE",""),
                                       //new SqlParameter("@LUXURYTAXAMT",""),
                                       //new SqlParameter("@ROUNDOFFAMT",""),
                                       //new SqlParameter("@TAXDISCOUNT",""),
                                       //new SqlParameter("@NONTAXDISCOUNT",""),
                                       //new SqlParameter("@TAXDISRATE",""),
                                       //new SqlParameter("@NONTAXDISRATE",""),
                                       //new SqlParameter("@VATAMT",""),
                                       new SqlParameter("@TOTALAMT",txtGrandTotal.Text.Trim())
                                   };
                int result = DU.executeprocedure("USP_IVC_SavePurchaseOrder_Total", sparam);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/Welcome.aspx");
    }
}






